<?php
namespace app\yunda\admin;

use app\common\builder\ZBuilder;
use app\yunda\model\Order as OrderModel;
use app\yunda\model\User;
use app\yunda\model\Danhao;
use app\yunda\model\Category;
use think\Db;

class Order extends Base{
    public function index($type=1)
    {
        // 获取查询和排序规则
        $map = $this->getMap();
        $order = $this->getOrder();

        //根据订单状态查询订单
        switch ($type){
            case 1:$map['order_status']=1;break;//待确认
            case 2:$map['order_status']=2;break;//待取件
            case 3:$map['order_status']=3;break;//已取件
            case 4:$map['order_status']=4;break;//已派送
            case 5:$map['order_status']=5;break;//已取消
        }

        //按取件地区排序
        $paixu=input('paixu');
        if(isset($paixu) && $paixu==1) $order.='send_address desc';
//        halt($order);
        //操作按钮
        $btn_1=[//派单按钮
            'title' => '指派订单给员工',
            'icon'  => 'fa fa-fw fa-hand-o-up',
            'class' => 'btn btn-xs btn-default ajax-get',
            'href'  => url('order_ok', ['id' => '__id__'])
        ];
        $btn_2=[//取消订单按钮
            'title' => '取消订单',
            'icon'  => 'fa fa-fw fa-times-circle',
            'class' => 'btn btn-primary ajax-post',//选中多个数据必须是post请求
            'href'  => url('cancel')
        ];
        $btn_3=[//按地区排序
            'title' => '按取件地址排序',
            'icon'  => 'fa fa-fw fa-hand-o-up',
            'class' => 'btn btn-primary get',//选中多个数据必须是post请求+
            'href'  => url('order/index',['paixu'=>1])
        ];
        $list_tab=$this->orderMenu();//获取选择菜单


       // halt($map);
        $data = Db::view('yd_order')
            ->view('yd_category',['name as order_type_name'],'yd_category.id=yd_order.order_type')
            ->where($map)
            ->order($order)
            ->order('yd_order.id desc')
            ->paginate()->each(function($item){
                $arr=['否','是'];
                $item['is_pay']=$arr[$item['is_pay']];
                $item['is_price']=$arr[$item['is_price']];
                $item['address1']=$item['get_name'].'<br/>'.$item['get_phone'].'<br/>'.$item['get_address'];
                $item['address2']=$item['send_name'].'<br/>'.$item['send_phone'].'<br/>'.$item['send_address'];
                $user=User::get(['openid'=>$item['openid']]);
                $item['username']=$user['nickname'];
                $ywy=$user=User::get($item['pai_id']);
                $item['yewuyuan']=$ywy['nickname'];
                return $item;
            });
//        halt($data);
        return ZBuilder::make('table')
            ->setTableName('yd_order')  //需要修改 这里修改正确可以直接修改字段 删除
            ->setTabNav($list_tab,  $type)
            ->addColumns([
                ['id','id'],
                ['username','用户'],
                ['order_id','订单号'],
                ['yewuyuan','快递员工'],
                ['address1','收件人地址'],
                ['address2','发件人地址'],
                ['order_type_name','快件类型'],
                ['weight','重量预估/kg'],
                ['is_pay','是否到付'],
                ['is_price','是否保价'],
                ['ask','其他要求'],
                ['pay_money','应付金额'],
                ['yj_money','原价'],
                ['is_pay_money','支付状态','status','',['未支付:danger','已支付:primary']],
                ['create_time','创建时间','datetime'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('order_ok',$btn_1,['area' => ['400px', '40%']])
            ->addRightButton('edit',[],[])
            ->addTopButton('order_address',$btn_3)
            ->addTopButton('cancel',$btn_2)
            ->addTopButtons(['delete'])
            ->setRowList($data)
            ->addFilter(['order_status'],['未签收','已签收','已取消'])
            ->addFilter(['real_name'=>'yd_user.name'])
            ->addFilter(['pai_name'=>'yd_user.name'])
            ->addTimeFilter('yd_order.create_time') // 添加时间段筛选
            ->setSearch(['id' => 'ID', 'order_id' => '订单号'])
            ->fetch();
    }

    public function edit($id=null){
        if($this->request->isPost()){
            $data = request()->post();
//            $result = $this->validate($data,'Goods');
//            if($result!==true) $this->error($result);
            OrderModel::update($data);
            $this->success('保存成功', null, '_parent_reload');
        }
        $data = OrderModel::get($id);
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['radio','order_status','订单状态','',['未签收','已签收','已取消']],
            ])
            ->setFormData($data)
            ->fetch();
    }

    //指派给快递员
    public function order_ok($id=null)
    {
        if(empty($id))return json('参数错误');
        $row=OrderModel::get($id);
        if(empty($row)) return json('该订单不存在');
        if($row['pai_id']>0)return json('该订单已分配快递员');
        if($row['order_status']==5) return json('该订单已取消');
        if($row['pai_id']==0){
            if($this->request->isPost()){
                $data=request()->post();
                if(empty($data['pai_id']))$this->error('指派员工不能为空');
                OrderModel::update($data);
                $this->success('指派成功', null, '_parent_reload');
            }
            $info=['id'=>$id];
            // 显示编辑页面
            return ZBuilder::make('form')
                ->addFormItems([
                    ['hidden', 'id'],
                    ['hidden','order_status', 2],
                    ['select','pai_id','快递员工','',User::getYuanGong($row['openid'])],
                ])
                ->setFormData($info)
                ->setBtnTitle('submit', '确认')
                ->fetch();
        }
    }

    //批量指派给快递员
    public function order_ok_all($ids=null)
    {
        //获取订单状态
        $order = OrderModel::where(['id' => ['in', $ids]])->order('create_time desc')->select();
        $arr = [];
        foreach ($order as $k => $v) {
            switch ($v['order_status']) {
                case 1:
                    $msg='ID为'.$v['id'].'的订单已签收';
                    $this->error($msg);
                    break;
                case 2:
                    $msg='ID为'.$v['id'].'的订单已取消';
                    $this->error($msg);
                    break;
                default:
                    $arr[]=$v['id'];
            }
            if ($v['pai_id'] > 0) $this->error('已经指派快递员');
        }
        $data = request()->only(['pai_id','type']);
        //halt(1);
        if ($this->request->isPost() && isset($data['type']) && $data['type']=='form') {
            if (empty($data['pai_id'])) $this->error('指派员工不能为空');
            halt($data);
            $b = OrderModel::update($data);
            $this->success('确认成功', null, '_parent_reload');

        }
        // 显示编辑页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','type','form'],
                ['select', 'pai_id', '快递员工', '', User::getYuanGong()],
            ])
            ->setBtnTitle('submit', '确认')
            ->fetch();


    }

    //取消订单
    public function cancel($ids=null)
    {
       $order=new OrderModel();
       $arr=[];
       foreach ($ids as $k=>$v){
            $row=$order::get($v);
            //待确认订单和待取件订单可取消
            if($row['order_status']!=1 || $row['order_status']!=2) $this->error('该订单不能取消');
            $arr[$k]['id']=$v;
            $arr[$k]['order_status']=5;

       }
       $order->saveAll($arr);
       $this->success('取消订单成功');
    }

//    public function delete($record = [])
//    {
//        foreach ($record as $v){
//            OrderModel::destroy(['id'=>$v]);
//        }
//        $this->success('删除成功');
//    }
}